package com.kingsoft.dc.khaos.module.spark.util

import scala.util.matching.Regex

/**
 *
 * create by gs 2020/10/12 
 *
 */
object StringHandleUtils {
  /**
   * 替换字符前缀
   *
   * @param str
   * @param literal
   * @param replacement
   * @return
   */
  def replacePrefix(str: String, literal: String, replacement: String): String = {
    if (str.startsWith(literal)) {
      replaceFirst(str,literal,replacement)
    } else {
      str
    }
  }

  /**
   * 替换字符后缀
   *
   * @param str
   * @param literal
   * @param replacement
   * @return
   */
  def replaceSuffix(str: String, literal: String, replacement: String): String = {
    if (str.endsWith(literal)) {
      replaceLast(str,literal,replacement)
    } else {
      str
    }
  }

  /**
   * 替换字符前后缀
   *
   * @param str
   * @param literal
   * @param replacement
   * @return
   */
  def replacePrefixAndSuffix(str: String, literal: String, replacement: String): String = {
    if (str.startsWith(literal) && str.endsWith(literal)) {
      val first = replaceFirst(str, literal, replacement)
      if(first.endsWith(literal)){
        replaceLast(first, literal, replacement)
      }else{
        str
      }
    } else {
      str
    }
  }

  /**
   * 替换第一个匹配的字符（包含元字符）
   *
   * @param str
   * @param literal
   * @param replacement
   * @return
   */
  def replaceFirst(str: String, literal: String, replacement: String): String = {
    val arg1 = Regex.quote(literal)
    val arg2 = Regex.quoteReplacement(replacement)
    str.replaceFirst(arg1, arg2)
  }

  /**
   * 替换最后一个匹配的字符（包含元字符）
   *
   * @param str
   * @param literal
   * @param replacement
   * @return
   */
  def replaceLast(str: String, literal: String, replacement: String): String = {
    val sb = new StringBuilder(str)
    sb.replace(str.lastIndexOf(literal), str.lastIndexOf(literal) + literal.length, replacement).toString()
  }
}
